package com.chazz.servlet;

import com.chazz.entity.User;
import com.chazz.service.UserService;
import com.chazz.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/registered.do")
public class RegisteredServlet extends HttpServlet {
    private static UserService userService=new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        Integer sex = Math.random() > 0.5 ? 1 : 0;
        ;
        String yzm = req.getParameter("yzm");
        //获session中的stringBuilder
        HttpSession session = req.getSession();
        String stringBuilder = (String) session.getAttribute("stringBuilder");
        PrintWriter out = resp.getWriter();
        if (username == null && password == null && email == null && phone ==null && sex ==null) {
            out.write("null");
        }else {
            if (stringBuilder.equals(yzm)) {
                User user = new User();
                try {
                    user.setId(userService.findUserFinalId() + 1);
                    user.setUsername(username);
                    user.setPassword(password);
                    user.setEmail(email);
                    user.setSex(sex);
                    user.setPhone(phone);
                    userService.addUser(user);
                    out.write("true");
                    resp.sendRedirect("login.jsp");
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }

            } else {
                out.write("false");

            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
